import { Folder } from '@/types/global';
import { currentFolder } from '@/views/bus';
import { findById } from '@/store/program/utils';
import { selectedKey, update } from './bus';

export const dragover = (e: MouseEvent) => {
  e.preventDefault();
};
export const dragStart = (item: Folder) => {
  const e = window.event as DragEvent;
  const ids = JSON.stringify(Array.from(selectedKey.value));
  e.dataTransfer?.setData('ids', ids);
};
/* 拖拽，删除且增加 */
export const drop = (item: Folder) => {
  /* 处理文件夹 */
  if (item.type === 'folder' && item.children) {
    const e = window.event as DragEvent;
    const ids: Array<string> = JSON.parse(e.dataTransfer?.getData('ids') || '');
    /* 删除 */
    ids.forEach((v) => {
      const target = findById(v);
      if (target && item.children) {
        item.children.push(target);
        update(item);
      }
      currentFolder.value.children = currentFolder.value.children?.filter(
        (m) => {
          return m.id !== v;
        }
      );
    });
  } else if (item.type === 'file') {
    /* 处理文件,排序 */
    const current = findById(Array.from(selectedKey.value)[0]);
    const target = findById(item.id);

    if (!current || !target) return;
    const temp = current.sort;
    current.sort = target.sort;
    target.sort = temp;
  }
};
